package santeclair.owap.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import santeclair.lunar.framework.dao.jpa.impl.FwkGenericJpaDAO;
import santeclair.owap.dao.PartenaireDao;
import santeclair.owap.domain.Application;
import santeclair.owap.domain.Partenaire;

public abstract class AbstractPartenaireDao extends FwkGenericJpaDAO<Partenaire> implements PartenaireDao {

    /** {@inheritDoc} */
    @Override
    public Class<Partenaire> getEntityClass() {
        return Partenaire.class;
    }

    /** {@inheritDoc} */
    public abstract EntityManager getEntityManager();

    /** {@inheritDoc} */
    public Boolean checkApplicationPart(String idPart, String idAppli) {
        final StringBuilder sbJpql = new StringBuilder("SELECT count(app) FROM ")
                        .append(Partenaire.class.getSimpleName()).append(" part ")
                        .append(" INNER JOIN part.applications app ")
                        .append(" WHERE app.nom = :appli")
                        .append(" AND part.idPart = :nom");
        TypedQuery<Long> query = getEntityManager().createQuery(sbJpql.toString(), Long.class)
                        .setParameter("nom", idPart)
                        .setParameter("appli", idAppli);

        return query.getSingleResult() > 0;
    }

    /** {@inheritDoc} */
    public List<Partenaire> rechercheParCharte(String idCharte) {
        String jpql = "SELECT p FROM Partenaire p " +
                        "INNER JOIN p.chartes c " +
                        "WHERE c.code = :idCharte";
        TypedQuery<Partenaire> query = getEntityManager().createQuery(jpql, getEntityClass());
        query.setParameter("idCharte", idCharte);
        return query.getResultList();
    }

    /**
     * {@inheritDoc}
     */
    public void addPartenaire(String nomApplication, Partenaire part) {
        Application bean = getEntityManager().getReference(Application.class, nomApplication);
        bean.getPartenaires().add(part);
        getEntityManager().merge(bean);
        getEntityManager().flush();
    }

    /**
     * {@inheritDoc}
     */
    public void removePartenaire(String nomApplication, Partenaire part) {
        Application bean = getEntityManager().getReference(Application.class, nomApplication);
        bean.getPartenaires().remove(part);
        getEntityManager().merge(bean);
        getEntityManager().flush();
    }
}
